#!/bin/bash

# 增强版数据库启动脚本 - 安全强化和连接可靠性
# 支持三个主数据库和一个备用数据库，包含安全检查和自动修复

echo "🚀 增强版数据库启动脚本启动..."
echo "🔒 安全强化模式已启用"

# 检查是否在宝塔面板环境
if [ -d "/www/server" ] && [ -d "/www/server/panel" ]; then
    echo "🔧 检测到宝塔面板环境"
    BT_PANEL=true
else
    echo "💻 检测到普通Linux环境"
    BT_PANEL=false
fi

# ==================== 安全检查 ====================
echo ""
echo "🔍 执行安全检查..."

# 检查环境变量文件
if [ ! -f ".env.secure" ]; then
    echo "⚠️ 警告: 安全环境变量文件 .env.secure 不存在"
    echo "💡 将使用默认配置，建议创建安全配置文件"
    if [ -f ".env" ]; then
        echo "📄 使用默认 .env 文件"
        # 安全加载环境变量
        while IFS='=' read -r key value; do
            # 跳过注释和空行
            [[ $key =~ ^#.*$ ]] || [[ -z $key ]] && continue
            # 移除引号并设置变量
            value=$(echo "$value" | sed "s/^['\"]\(.*\)['\"]$/\\1/")
            export "$key"="$value"
        done < ".env"
    else
        echo "❌ 错误: 没有找到环境变量文件"
        exit 1
    fi
else
    echo "✅ 安全环境变量文件已找到"
    # 安全加载安全配置
    while IFS='=' read -r key value; do
        # 跳过注释和空行
        [[ $key =~ ^#.*$ ]] || [[ -z $key ]] && continue
        # 移除引号并设置变量
        value=$(echo "$value" | sed "s/^['\"]\(.*\)['\"]$/\\1/")
        export "$key"="$value"
    done < ".env.secure"
fi

# 检查密码强度
check_password_strength() {
    local password=$1
    local var_name=$2
    
    if [ ${#password} -lt 12 ]; then
        echo "⚠️ 警告: $var_name 密码长度不足12位"
        return 1
    fi
    
    if ! [[ "$password" =~ [A-Z] ]] || ! [[ "$password" =~ [a-z] ]] || ! [[ "$password" =~ [0-9] ]] || ! [[ "$password" =~ [!@#$%^&*(),.?\":{}|<>] ]]; then
        echo "⚠️ 警告: $var_name 密码复杂度不足（需要大小写字母、数字、特殊字符）"
        return 1
    fi
    
    echo "✅ $var_name 密码强度检查通过"
    return 0
}

# 检查默认密码
if [ "$DB_PASSWORD" = "password" ] || [ "$DB_PASSWORD" = "ChangeThisPassword123!@#" ]; then
    echo "❌ 错误: 请修改默认的数据库密码"
    echo "💡 建议使用强密码生成器生成新密码"
    exit 1
fi

if [ "$REDIS_PASSWORD" = "" ] || [ "$REDIS_PASSWORD" = "ChangeRedisPassword456!@#" ]; then
    echo "❌ 错误: 请设置Redis密码"
    echo "💡 Redis在生产环境中必须设置密码"
    exit 1
fi

# 检查JWT密钥
if [ "$JWT_SECRET" = "your-super-secret-jwt-key-change-in-production" ] || [ "$JWT_SECRET" = "SuperSecureJWTKeyChangeInProduction123!@#" ]; then
    echo "❌ 错误: 请修改默认的JWT密钥"
    echo "💡 JWT密钥在生产环境中必须修改"
    exit 1
fi

# ==================== 数据库服务启动 ====================

start_database_service() {
    local service_name=$1
    local systemd_service=$2
    local process_name=$3
    local friendly_name=$4
    
    echo ""
    echo "🗄️ 启动 $friendly_name..."
    
    if [ "$BT_PANEL" = true ]; then
        # 宝塔面板环境
        if systemctl is-active --quiet "$systemd_service"; then
            echo "✅ $friendly_name 服务已在运行"
            return 0
        else
            echo "🚀 启动 $friendly_name 服务..."
            sudo systemctl start "$systemd_service"
            sudo systemctl enable "$systemd_service" 2>/dev/null || true
            
            # 等待服务启动
            sleep 5
            
            if systemctl is-active --quiet "$systemd_service"; then
                echo "✅ $friendly_name 服务启动成功"
                return 0
            else
                echo "❌ $friendly_name 服务启动失败"
                return 1
            fi
        fi
    else
        # 普通Linux环境
        if pgrep -x "$process_name" > /dev/null; then
            echo "✅ $friendly_name 进程已在运行"
            return 0
        else
            echo "💡 普通环境：请确保 $friendly_name 已安装并启动"
            echo "💡 安装命令参考:"
            case "$service_name" in
                "postgresql")
                    echo "   安装: sudo apt-get install postgresql postgresql-contrib"
                    echo "   启动: sudo systemctl start postgresql"
                    ;;
                "redis")
                    echo "   安装: sudo apt-get install redis-server"
                    echo "   启动: sudo systemctl start redis-server"
                    ;;
                "mongodb")
                    echo "   安装: 参考MongoDB官方文档"
                    echo "   启动: sudo systemctl start mongod"
                    ;;
            esac
            return 1
        fi
    fi
}

# 启动PostgreSQL
start_database_service "postgresql" "postgresql" "postgres" "PostgreSQL"
PG_START_RESULT=$?

# 启动Redis
start_database_service "redis" "redis" "redis-server" "Redis"
REDIS_START_RESULT=$?

# 启动MongoDB
start_database_service "mongodb" "mongod" "mongod" "MongoDB"
MONGO_START_RESULT=$?

# ==================== SQLite备用数据库 ====================
echo ""
echo "💾 准备SQLite备用数据库..."

# 创建数据目录
mkdir -p data
mkdir -p logs

# 检查SQLite数据库文件
if [ -f "data/bike_wholesale.db" ]; then
    echo "✅ SQLite备用数据库已存在"
    SQLITE_EXISTS=true
else
    echo "📝 创建SQLite备用数据库..."
    # 使用增强版初始化脚本
    if [ -f "scripts/init-sqlite-enhanced.js" ]; then
        node scripts/init-sqlite-enhanced.js
    else
        node scripts/init-sqlite.js
    fi
    
    if [ -f "data/bike_wholesale.db" ]; then
        echo "✅ SQLite备用数据库创建成功"
        SQLITE_EXISTS=true
    else
        echo "❌ SQLite备用数据库创建失败"
        SQLITE_EXISTS=false
    fi
fi

# ==================== 数据库连接测试 ====================
echo ""
echo "🔗 执行数据库连接测试..."

test_postgresql_connection() {
    if command -v psql &> /dev/null; then
        echo "🔍 测试PostgreSQL连接..."
        if PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT NOW();" &> /dev/null; then
            echo "✅ PostgreSQL连接测试通过"
            return 0
        else
            echo "❌ PostgreSQL连接测试失败"
            return 1
        fi
    else
        echo "💡 psql命令不可用，跳过PostgreSQL连接测试"
        return 2
    fi
}

test_redis_connection() {
    if command -v redis-cli &> /dev/null; then
        echo "🔍 测试Redis连接..."
        if [ -n "$REDIS_PASSWORD" ]; then
            if redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" -a "$REDIS_PASSWORD" ping &> /dev/null; then
                echo "✅ Redis连接测试通过"
                return 0
            else
                echo "❌ Redis连接测试失败"
                return 1
            fi
        else
            if redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" ping &> /dev/null; then
                echo "✅ Redis连接测试通过（无密码）"
                return 0
            else
                echo "❌ Redis连接测试失败"
                return 1
            fi
        fi
    else
        echo "💡 redis-cli命令不可用，跳过Redis连接测试"
        return 2
    fi
}

# 执行连接测试
PG_TEST_RESULT=$(test_postgresql_connection; echo $?)
REDIS_TEST_RESULT=$(test_redis_connection; echo $?)

# ==================== 安全配置检查 ====================
echo ""
echo "🔒 执行安全配置检查..."

# 检查是否启用SSL
if [ "$DB_SSL" = "true" ]; then
    echo "✅ PostgreSQL SSL已启用"
else
    echo "⚠️ 建议: 在生产环境中启用PostgreSQL SSL"
fi

if [ "$REDIS_TLS" = "true" ]; then
    echo "✅ Redis TLS已启用"
else
    echo "⚠️ 建议: 在生产环境中启用Redis TLS"
fi

if [ "$MONGODB_SSL" = "true" ]; then
    echo "✅ MongoDB SSL已启用"
else
    echo "⚠️ 建议: 在生产环境中启用MongoDB SSL"
fi

# 检查防火墙配置
if command -v ufw &> /dev/null; then
    if ufw status | grep -q "Status: active"; then
        echo "✅ 防火墙已启用"
        
        # 检查数据库端口是否开放
        if ufw status | grep -q "5432/tcp"; then
            echo "⚠️ 警告: PostgreSQL端口5432对公网开放"
        fi
        if ufw status | grep -q "6379/tcp"; then
            echo "⚠️ 警告: Redis端口6379对公网开放"
        fi
        if ufw status | grep -q "27017/tcp"; then
            echo "⚠️ 警告: MongoDB端口27017对公网开放"
        fi
    else
        echo "⚠️ 警告: 防火墙未启用"
    fi
else
    echo "💡 ufw命令不可用，跳过防火墙检查"
fi

# ==================== 数据库状态报告 ====================
echo ""
echo "📊 增强版数据库状态报告:"
echo "=".repeat(60)

# PostgreSQL状态
if [ "$BT_PANEL" = true ]; then
    PG_STATUS=$(systemctl is-active postgresql)
else
    if pgrep -x "postgres" > /dev/null; then
        PG_STATUS="active"
    else
        PG_STATUS="inactive"
    fi
fi

if [ "$PG_TEST_RESULT" -eq 0 ]; then
    echo "✅ PostgreSQL: $PG_STATUS (连接测试通过)"
elif [ "$PG_TEST_RESULT" -eq 2 ]; then
    echo "🔵 PostgreSQL: $PG_STATUS (未测试)"
else
    echo "❌ PostgreSQL: $PG_STATUS (连接测试失败)"
fi

# Redis状态
if [ "$BT_PANEL" = true ]; then
    REDIS_STATUS=$(systemctl is-active redis)
else
    if pgrep -x "redis-server" > /dev/null; then
        REDIS_STATUS="active"
    else
        REDIS_STATUS="inactive"
    fi
fi

if [ "$REDIS_TEST_RESULT" -eq 0 ]; then
    echo "✅ Redis: $REDIS_STATUS (连接测试通过)"
elif [ "$REDIS_TEST_RESULT" -eq 2 ]; then
    echo "🔵 Redis: $REDIS_STATUS (未测试)"
else
    echo "❌ Redis: $REDIS_STATUS (连接测试失败)"
fi

# MongoDB状态
if [ "$BT_PANEL" = true ]; then
    MONGO_STATUS=$(systemctl is-active mongod)
else
    if pgrep -x "mongod" > /dev/null; then
        MONGO_STATUS="active"
    else
        MONGO_STATUS="inactive"
    fi
fi
echo "🔵 MongoDB: $MONGO_STATUS"

# SQLite状态
if [ "$SQLITE_EXISTS" = true ]; then
    echo "✅ SQLite备用: active"
else
    echo "❌ SQLite备用: inactive"
fi

echo "=".repeat(60)

# ==================== 最终状态评估 ====================
echo ""
if ( [ "$PG_TEST_RESULT" -eq 0 ] || [ "$PG_TEST_RESULT" -eq 2 ] ) && \
   ( [ "$REDIS_TEST_RESULT" -eq 0 ] || [ "$REDIS_TEST_RESULT" -eq 2 ] ) && \
   [ "$SQLITE_EXISTS" = true ]; then
    echo "🎉 增强版数据库服务启动完成！"
    echo "✅ 至少有一个数据库服务可用"
    
    # 生成安全报告
    echo ""
    echo "🔒 安全建议报告:"
    echo "-".repeat(40)
    echo "1. ✅ 密码强度检查完成"
    echo "2. 🔒 建议启用SSL/TLS加密"
    echo "3. 🔒 建议配置防火墙规则"
    echo "4. 🔒 建议定期备份数据库"
    echo "5. 🔒 建议启用数据库审计"
    echo "-".repeat(40)
    
else
    echo "⚠️ 警告: 部分数据库服务不可用"
    echo "💡 应用将使用可用的数据库服务"
    
    if [ "$SQLITE_EXISTS" = true ]; then
        echo "💡 SQLite备用数据库可用，基本功能不受影响"
    else
        echo "❌ 严重: 所有数据库服务都不可用"
        echo "💡 应用将使用内存存储（功能受限）"
    fi
fi

# ==================== 宝塔面板优化 ====================
if [ "$BT_PANEL" = true ]; then
    echo ""
    echo "🔧 宝塔面板优化配置..."
    
    # 创建增强版数据库管理脚本
    cat > /tmp/bt-database-manager-enhanced.sh << 'EOF'
#!/bin/bash
# 宝塔面板增强版数据库管理脚本

case "$1" in
    start)
        systemctl start postgresql
        systemctl start redis
        systemctl start mongod
        echo "数据库服务已启动"
        ;;
    stop)
        systemctl stop postgresql
        systemctl stop redis
        systemctl stop mongod
        echo "数据库服务已停止"
        ;;
    restart)
        systemctl restart postgresql
        systemctl restart redis
        systemctl restart mongod
        echo "数据库服务已重启"
        ;;
    status)
        echo "PostgreSQL: $(systemctl is-active postgresql)"
        echo "Redis: $(systemctl is-active redis)"
        echo "MongoDB: $(systemctl is-active mongod)"
        ;;
    backup)
        echo "执行数据库备份..."
        # 这里可以添加备份逻辑
        ;;
    security-check)
        echo "执行安全检查..."
        # 这里可以添加安全检查逻辑
        ;;
    *)
        echo "用法: $0 {start|stop|restart|status|backup|security-check}"
        ;;
esac
EOF
    
    chmod +x /tmp/bt-database-manager-enhanced.sh
    echo "✅ 增强版宝塔面板数据库管理脚本已创建: /tmp/bt-database-manager-enhanced.sh"
fi

# ==================== 启动完成 ====================
echo ""
echo "🚀 增强版数据库启动脚本执行完成！"
echo ""
echo "💡 管理命令:"
if [ "$BT_PANEL" = true ]; then
    echo "   启动所有数据库: sudo systemctl start postgresql redis mongod"
    echo "   查看数据库状态: sudo systemctl status postgresql redis mongod"
    echo "   数据库管理脚本: /tmp/bt-database-manager-enhanced.sh"
else
    echo "   请根据您的环境使用相应的数据库管理命令"
fi

echo ""
echo "🔒 安全提醒:"
echo "   1. 定期修改数据库密码"
echo "   2. 启用SSL/TLS加密"
echo "   3. 配置防火墙规则"
echo "   4. 定期备份重要数据"

exit 0